import requests
from lxml import etree
import json
import jsonpath

######在抖音app，点击转发，点击复制链接后进行下一步########

#需要解析的短视频网址，其他网址请直接获取短链接后替换到url处：
#url = 'https://v.douyin.com/JPa1xhq/'

url = input('请输入视频短链接:')

########获取视频代码########

headers = {
    'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}

page_text = requests.get(url=url, headers=headers).text
tree = etree.HTML(page_text)
Video_url = tree.xpath('/html/head/link[1]/@href')
ID = Video_url[0].split('/')[-1]

##########获取视频标题，设置保存名################
title = tree.xpath('/html/head/title/text()')[0].split('#')[0]
File_wt_name = title+'_水印版.mp4'
File_nwt_name = title+'.mp4'


print ("解析中................")
########获取视频代码########
Json_url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids='+ID
Json = requests.get(url=Json_url, headers=headers).text
Json_text = json.loads(Json)
video = jsonpath.jsonpath(Json_text,'$..play_addr.url_list')
watermark = video[0][0]
no_watermark = "https://aweme.snssdk.com/aweme/v1/play/"+watermark.split("/")[-1]
print ("无水印版本：" + no_watermark)
print ("带水印版本：" + watermark)

########下载下来########

choose =  int(input("下载无水印版本请按【1】;"
               "有水印版本请按【2】:"))

print ("-----------------------------------------------------------------")


#######老铁们注意了，上面2行原本忘记加int，于是下面判断的1，还是2不是同一种类型，容易出错#######
if choose == 1:
    r = requests.get(url=no_watermark, headers=headers)
    with open(File_nwt_name, "wb") as dy:
      dy.write(r.content)
else:
    r = requests.get(url=watermark, headers=headers)
    with open(File_wt_name, "wb") as dy:
        dy.write(r.content)

